// server.js
// where your node app starts

// init project
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
global.urlList = [];

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

// we've started you off with Express, 
// but feel free to use whatever libs or frameworks you'd like through `package.json`.

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

app.post("/api/shorturl/new",(req, res)=>{
  const { url } = req.body;
  if(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(url)){    
    const index = global.urlList.findIndex(item => item.original_url === url);
    let urlObj;  
    if(index === -1 ){
      urlObj = {original_url:url, short_url: global.urlList.length + 1}
      global.urlList.push(urlObj);
    } else {
      urlObj = global.urlList[index];
    }        
    console.log(urlObj);
    res.json(urlObj);
  }  else {
    res.json({"error":"invalid URL"});
  }
})

app.get("/api/shorturl/:index", (req, res) => {    
  const urlObj = global.urlList[req.params.index - 1];
  if(!urlObj) {
    return res.json({"error":"invalid URL"});
  }
  res.redirect(global.urlList[req.params.index - 1].original_url);
});

// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' + listener.address().port);
});
